package com.eipc;


import org.androidpn.sdk.Constants;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;

import com.eipc.info.R;
import com.eipc.model.ImportNotice;
import com.eipc.model.SerInfoResponse;
import com.eipc.util.DBHelper;
import com.eipc.util.HttpManager;
import com.eipc.util.Tools;

public class FetchNoticeService extends Service {
	private DBHelper mDB;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
//		mDB = new DBHelper(this);
		mDB = DBHelper.getInstance(this);
		 
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		new PollingTask().execute();
		Log.e("-----------do FetchNoticeService-----------------",Tools.getCurrentTimeString());
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	class PollingTask extends AsyncTask<Void, Void, Void>{
		@Override
		protected Void doInBackground(Void... params) {
			try {
				SharedPreferences sdkPreferences = getSharedPreferences(
						Constants.SDK_PREFERENCES, Context.MODE_PRIVATE);
				String mobileID = sdkPreferences.getString(
						Constants.XMPP_USERNAME, "");
//				String maxID    = sdkPreferences.getString(Constants.MaxId,"0");
				// 
				
				String strIDs;
				
				if ( " ".equals(mDB.GetIMMaxID())||mDB.GetIMMaxID()==null)
					strIDs = String.valueOf(0);
				else
					strIDs = mDB.getIMIDs();
				Log.i("Start Get Im, strIDs",strIDs);
//				if (strIDs == null || strIDs == "")
//					strIDs = String.valueOf(0);
				SerInfoResponse imSir = HttpManager.execSerIMSql(
						getString(R.string.url_exec_serSql), mobileID,
						strIDs, Constants.LOAD_MODEL_IM);
				if (imSir != null) {
					ImportNotice[] os = (ImportNotice[]) imSir.os;

					mDB.insertImportNotice(os,String.valueOf(0));
				}
				

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

		}
		
	}
}
